package de.grosjohann.android.feuerwehr;

import java.util.List;

import android.location.Address;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import de.grosjohann.android.feuerwehr.domain.Fahrzeug;
import de.grosjohann.android.feuerwehr.map.MarkerOverlay;
import de.grosjohann.android.feuerwehr.util.LocationUtil;

public class MapsActivity
  extends MapActivity {

  public static final String LOCATION = "feuerwehr.LOCATION";
  public static final String OBJECT = "feuerwehr.OBJECT";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);

    MapView mapView = (MapView) findViewById(R.id.map);
    mapView.setBuiltInZoomControls(true);

    Bundle bundle = getIntent().getExtras();
    if ((bundle != null) && bundle.containsKey(OBJECT) && (bundle.getSerializable(OBJECT) instanceof Fahrzeug)) {
      Fahrzeug f = (Fahrzeug) bundle.getSerializable(OBJECT);
      TextView tvDesc = (TextView) findViewById(R.id.tvLocDescription);
      tvDesc.setText(f.getDescription());

      TextView tvKennung = (TextView) findViewById(R.id.tvLocKennung);
      tvKennung.setText(f.getIdentifier());
    }

    if ((bundle != null) && bundle.containsKey(LOCATION)) {
      String loc = bundle.getString(LOCATION);

      setMarker(mapView, loc);

      setLocationText(loc);
    }

  }

  @Override
  protected boolean isRouteDisplayed() {
    return false;
  }

  private void setMarker(MapView mapView, String loc) {
    GeoPoint gp = LocationUtil.getGeoPoint(loc);
    mapView.getController().animateTo(gp);
    mapView.getController().setCenter(gp);
    mapView.getController().setZoom(17);

    List<Overlay> mapOverlays = mapView.getOverlays();

    MarkerOverlay overlay = new MarkerOverlay(getApplicationContext(), gp);
    mapOverlays.add(overlay);
  }

  private void setLocationText(String loc) {
    TextView tvLocAddress = (TextView) findViewById(R.id.tvLocAddress);

    if (LocationUtil.LOC_HOME.equals(loc)) {
      tvLocAddress.setText(R.string.lblLocCurrHome);
    } else {
      Address address = LocationUtil.getAddress(getApplicationContext(), loc);

      if (address == null) {
        tvLocAddress.setVisibility(View.GONE);
      } else {
        tvLocAddress.setVisibility(View.VISIBLE);

        String adr = address.getAddressLine(0) + ", " + address.getLocality();
        tvLocAddress.setText(adr);
      }
    }
  }

}